package com.sgb.kjwl.view.ui.activity.transport;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAddressSelectionBinding;
import com.sgb.kjwl.model.entity.transport.AMapAddressEntity;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.adapter.transport.RecommendAddressListAdapter;
import com.sgb.link.router.PathTransport;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick2;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.NumberUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * Describe:    选择地址
 * Author:  yangLei
 * Date:    2021/8/13
 */
@Route(path = PathTransport.AddressSelectionActivity)
public class AddressSelectionActivity extends AppActivity implements PoiSearch.OnPoiSearchListener {
    public static final String FROM_MAIN_PAGE = "首页";
    public static final String FROM_FIND_CAR = "找车";
    public static final String FROM_FIND_GOODS = "找货";

    @Autowired(name = RouterKey.STRING, desc = "当前城市")
    public String mCurrCity;
    @Autowired(name = RouterKey.INT, desc = "地址类型")
    public int type = 0;//0(起点)   1(终点)
    @Autowired(name = RouterKey.TYPE, desc = "位置来源页")
    public String from;
    @Autowired(name = RouterKey.DATA, desc = "装货地址信息")
    public AMapAddressEntity loadingAddress;
    //地图搜索Poi类型
    private final static String POI_TYPE = "汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|" +
            "体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|" +
            "金融保险服务|公司企业|道路附属设施|公共设施";
    //搜索返回的地址数目
    private final int limit = 10;
    //搜索扩展字段 base表示只返回基础数据，all表示所有数据 ，默认 base
    private final String extensions = "all";
    //地址列表
    private List<AMapAddressEntity> mList = new ArrayList<>();
    //当前选中的位置信息
    private AMapAddressEntity selectEntity;
    private RecommendAddressListAdapter addressListAdapter;

    private ActivityAddressSelectionBinding mBinding;

    //当前定位位置信息
    private LatLng latLngLocation;

    private boolean IsViewCitySelector = false;//城市选择器是否显示


    @Override
    protected void init() {
        initViews();
        initEvents();
        initData();
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_address_selection);
    }

    private void initViews() {
        ARouter.getInstance().inject(AddressSelectionActivity.this);
        mBinding.actionBar.setTitle("选择地址");
        addressListAdapter = new RecommendAddressListAdapter(this, mList);
        mBinding.commendList.setLayoutManager(new LinearLayoutManager(this));
        mBinding.commendList.setAdapter(addressListAdapter);
        addressListAdapter.setOnItemClick(new AdapterOnItemClick2<AMapAddressEntity>() {
            @Override
            public void onItemClick(AMapAddressEntity entity, int position) {
                if (ClickUtils.isDoubleClick2())
                    return;
                selectEntity = entity;
                AddressHelper.getInstance().findCode(selectEntity);
                if (!TextUtils.isEmpty(from)) {
                    selectEntity.setType(type);
                    if (from.equals(FROM_MAIN_PAGE)) {
                        LogisticsEvent event = LogisticsEvent.make();
                        event.setMessageTag(EventConstant.EVENT_ADDRESS_SELECTED);
                        event.setObject(selectEntity);
                        EventBus.getDefault().post(event);

//                        if (type == 0) {
//                            ARouter.getInstance().build(PathTransport.MapFindingCarActivity)
//                                    .withParcelable(RouterKey.DATA, selectEntity)
//                                    .navigation();
//                        } else if (type == 1) {
//                            ARouter.getInstance().build(PathTransport.MapFindingCarActivity)
//                                    .withParcelable(RouterKey.DATA, loadingAddress)
//                                    .withParcelable(RouterKey.DATA1, selectEntity)
//                                    .navigation();
//                        }
                    }
                } else {
                    Intent intent = new Intent();
                    intent.putExtra(RouterKey.DATA, selectEntity);
                    intent.putExtra(RouterKey.INT, type);
                    setResult(200, intent);
                }
                finish();
            }
        });
    }

    private void initData() {
        if (loadingAddress != null && !TextUtils.isEmpty(loadingAddress.getCity())) {
            mCurrCity = loadingAddress.getCity();
            mBinding.cityName.setText(mCurrCity);
            mBinding.citySelectView.setCurrCity(mCurrCity);
            searchByCityAndKeyword("", mCurrCity);
        } else if (!TextUtils.isEmpty(mCurrCity)) {
            mBinding.cityName.setText(mCurrCity);
            mBinding.citySelectView.setCurrCity(mCurrCity);
            searchByCityAndKeyword("", mCurrCity);
        }
    }

    private void initEvents() {
        mBinding.cityName.setOnClickListener(this::onClick);
//        mBinding.citySelectView.setCheckedClickListener(name -> checkedCityResult(name.getCity()));
        mBinding.cleanEdit.setOnClickListener(this::onClick);
        mBinding.editAddress.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String keyWords = s.toString();
                if (TextUtils.isEmpty(keyWords)) {
                    mBinding.cleanEdit.setVisibility(View.GONE);
                } else {
                    mBinding.cleanEdit.setVisibility(View.VISIBLE);
                }
                searchByCityAndKeyword(keyWords, mCurrCity);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 选中城市
     *
     * @param name
     */
    private void checkedCityResult(String name) {
        if (!TextUtils.isEmpty(name)) {
            mBinding.cityName.setText(name);
            mCurrCity = name;
            viewSwitches(false);
            searchByCityAndKeyword(mBinding.editAddress.getText().toString(), name);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.city_name:
                ARouter.getInstance().build(PathTransport.LocationSelectionActivity)
                        .withString(RouterKey.STRING, mBinding.cityName.getText().toString())
                        .navigation(this, 201);
//                if (IsViewCitySelector) {
//                    viewSwitches(false);
//                } else {
//                    viewSwitches(true);
//                }
                break;

            case R.id.clean_edit:
                mBinding.editAddress.setText("");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == 201 && resultCode == 200) {
                AMapAddressEntity entity = data.getParcelableExtra(RouterKey.DATA);
                if (entity != null && !TextUtils.isEmpty(entity.getCity())) {
                    mCurrCity = entity.getCity();
                    mBinding.cityName.setText(mCurrCity);
                    String keyWord = mBinding.editAddress.getText().toString().trim();
                    searchByCityAndKeyword(keyWord, mCurrCity);
                }
            }
        }
    }

    /**
     * 切换城市选择弹窗
     *
     * @param show 是否隐藏城市选择器
     */
    private void viewSwitches(boolean show) {
        if (!show) {
            IsViewCitySelector = false;
            mBinding.citySelectView.setVisibility(View.GONE);
            mBinding.commendList.setVisibility(View.VISIBLE);
        } else {
            IsViewCitySelector = true;
            mBinding.citySelectView.setVisibility(View.VISIBLE);
            mBinding.commendList.setVisibility(View.GONE);
            hideSoftKeyboard(this);
        }
    }

    /**
     * 通过城市和关键字搜索地区
     */
    public void searchByCityAndKeyword(String keyword, String cityName) {
        //设置当前城市
        mCurrCity = cityName;
        PoiSearch.Query query = new PoiSearch.Query(keyword, POI_TYPE, cityName);
        query.setPageSize(limit);
        query.setPageNum(1);
        query.setExtensions(extensions);
        PoiSearch poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int code) {
        DialogHelper.dismissProgressDialog();
        if (code != 1000) {
            MLog.d("debug", "搜索失败");
            return;
        }
        //1000 成功
        mList.clear();
        //添加地址信息
        List<PoiItem> poiList = poiResult.getPois();
        if (poiList != null && poiList.size() > 0) {
            MLog.d("debug", "搜索成功");
            for (PoiItem poi : poiList) {
                //计算当前位置与定位点的距离
                float distance = 0;
                if (latLngLocation != null) {
                    LatLng current = new LatLng(poi.getLatLonPoint().getLatitude(), poi.getLatLonPoint().getLongitude());
                    distance = AMapUtils.calculateLineDistance(current, latLngLocation);
                }
                //添加当前位置信息
                mList.add(new AMapAddressEntity(poi.getProvinceName(), poi.getCityName(), poi.getAdName(), poi.getSnippet(),
                        poi.getTitle(), String.format("%s", NumberUtil.trim0(distance, 2)),
                        poi.getLatLonPoint().getLatitude(), poi.getLatLonPoint().getLongitude(),
                        poi.getProvinceCode(), poi.getCityCode(), poi.getAdCode()));
            }
            addressListAdapter.notifyDataSetChanged();
//            viewSwitches(false);
        } else {
            MToast.showToast(this, "没有匹配信息");
            MLog.d("debug", "没有搜到，请尝试其他关键词");
        }
    }


    @Override
    public void onPoiItemSearched(PoiItem poiItem, int code) {

    }

    /**
     * 隐藏软键盘(适用于Activity)
     */
    public static void hideSoftKeyboard(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
